package com.heima.common.exception;

import com.heima.common.dtos.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {


    /**
     * 对系统自定义异常的处理
     * */
    @ExceptionHandler(LeadException.class)
    public ResponseResult leadExceptionHandler(LeadException exception){
        return new ResponseResult(exception.getStatus(), exception.getMessage());
    }

    /**
     * 参数校验出现异常的处理
     * */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException exception){
        BindingResult bindingResult = exception.getBindingResult();
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        String msg = allErrors.stream().map(error -> error.getDefaultMessage()).collect(Collectors.joining(";"));
        return new ResponseResult(400, msg);
    }


    /**
     * 全局兜底的异常处理器
     * */
    @ExceptionHandler(Throwable.class)
    public ResponseResult throwableHandler(Throwable exception){
        log.error("全局处理器异常信息：{}", ExceptionUtils.getStackTrace(exception));
        return new ResponseResult(500, "服务端异常，请稍后重试");
    }



}
